const router = require("koa-router")()
const main = require("../models")
router.get("/login",async ctx=>{
    var arr = ['html','css','js']
    await ctx.render("login",{arr})
})
router.get("/register",async ctx=>{
    await ctx.render("register")
})
router.get("/home",async ctx=>{
    ctx.body = "首页"
})
router.post("/doRegister",async ctx=>{
    var {username,password} = ctx.request.body
    var userCollection = await main("user")
    var res = await userCollection.find({username}).toArray()
    // 1、判断用户名是否存在，存在就返回原来的页面
    if(res.length){
        ctx.body = "<script>alert('用户名已经存在');location.href='./register'</script>"
    }else{
        // 2、用户名不存在，注册进入首页
        await userCollection.insertOne({username,password})
        ctx.body = "<script>alert('注册成功，恭喜进入首页');location.href='/home'</script>"
    }
})
router.post("/doLogin",async ctx=>{
    var {username,password} = ctx.request.body
    var userCollection = await main("user")
    var res = await userCollection.find({username,password}).toArray()
    if(res.length){
        await ctx.redirect("/home")
    }else{
        ctx.body = "<script>alert('用户名或密码错误');location.href='/login'</script>"
    }
})
module.exports = router